package com.example.app.controller;

import com.example.app.config.LoginUser;
import com.example.app.entity.FriendRequest;
import com.example.app.entity.User;
import com.example.app.service.FriendService;
import jakarta.annotation.Resource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/friends")
public class FriendController {

    @Resource
    private FriendService friendService;

    @GetMapping("")
    public List<User> list() {
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return friendService.getFriends(principal.getUserId());
    }

    @PostMapping("/request")
    public FriendRequest sendRequest(@RequestBody Map<String, Long> body) {
        Long toUserId = body.get("toUserId");
        FriendRequest fr = new FriendRequest();
        LoginUser principal = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        fr.setSenderId(principal.getUserId());
        fr.setReceiverId(toUserId);
        fr.setStatus("PENDING");
        return friendService.insertFriendRequest(fr);
    }

    @GetMapping("/incoming")
    public List<FriendRequest> incoming() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return friendService.findFriendRequest(principal.getId(), "PENDING");
    }
}
